<?php

namespace common\filters;

/**
 * @author  shuang
 * @date    2017-2-24 7:58:31
 * @version V1.0
 * @desc    
 */
use Yii;
use yii\base\ActionFilter;
//use backend\models\LoginForm;
use frontendw\models\LoginForm;

class LoginFilter extends ActionFilter {

    public function beforeAction($action) {
        if (Yii::$app->user->isGuest) {
            if (Yii::$app->api->isweixin()) {
                $model = new LoginForm();
                if (Yii::$app->request->get("code")) {
                    $openid_info = Yii::$app->wechat->getOauth2AccessToken(Yii::$app->request->get("code"));
                    $model->wxopenid = $openid_info['openid'];
                    if (!$model->wlogin()) {
                        Yii::$app->controller->redirect(["site/signup"], 301);
                    }else{
                        Yii::$app->controller->redirect(["site/index","wxopenid"=>$openid_info['openid']]);
                    }
                } else {
                    $url = Yii::$app->wechat->getOauth2AuthorizeUrl(Yii::$app->request->getHostInfo() . Yii::$app->request->getUrl());
                    header("Location:$url");
                }
            } else {
                Yii::$app->user->logout();
                if ($action->id != "login") {
                    if ($action->id != "signup") {
                        Yii::$app->controller->redirect(["site/login"], 301);
                    }
                }
            }
        }
        if (!Yii::$app->user->isGuest) {
            if (Yii::$app->user->identity->froststatus == 1) {
                $frostmodel = \backend\models\MY_UserFrostRecord::find()->where("userid=:userid", [":userid" => Yii::$app->user->id])->orderBy("created_at desc")->one();
                if ($frostmodel && $frostmodel->frosted_at <= time()) {
                    Yii::$app->user->identity->froststatus = 0;
                    Yii::$app->user->identity->save();
                }
            }
        }
        return true;
    }

}
